import 'dart:async';
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/dao/collect_dao.dart';
import 'package:changxindianzishangwu/model/address_book_model.dart';
import 'package:changxindianzishangwu/pages/contacts/conversation_friend_page.dart';
import 'package:changxindianzishangwu/pages/message/chat/video_message_page.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/fade_router.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/get_contacts_widget.dart';
import 'package:changxindianzishangwu/widget/message/select_message_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_plugin_record/flutter_plugin_record.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_custom_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_image.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_image_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_sound_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_text_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_video_elem.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:w_popup_menu/w_popup_menu.dart';

import '../PhotoViewGalleryScreen.dart';
import '../checkbox_widget.dart';
import '../loding.dart';
import '../web_view.dart';

class MessageBodyWidget extends StatefulWidget {
  //消息
  List<V2TimMessage> messages = [];
  ScrollController controller;
  final String conversationID;
  final int type;
  final String userID;
  final String groupID;
  final Future<void> refrsh;
  final ValueChanged<String> name;
  bool checkMessage;
  V2TimConversation conversation;
  MessageBodyWidget(this.conversationID, this.type, this.userID, this.groupID,
      this.conversation,
      {Key key,
      this.messages,
      this.checkMessage = false,
      this.refrsh,
      this.name,
      this.controller})
      : super(key: key);

  @override
  _MessageBodyWidgetState createState() => _MessageBodyWidgetState();
}

class _MessageBodyWidgetState extends State<MessageBodyWidget> {
  List<V2TimMessage> currentMessageList = <V2TimMessage>[];
  bool hasNoRead;
  FlutterPluginRecord recordPlugin = new FlutterPluginRecord();
  List<V2TimImage> ee = [];
  int indexs = 0;
  getIndex(index) {
    for (int i = 0; i < ee.length; i++) {
      if (ee[i].UUID == index) {
        indexs = i;
      }
    }
    print(indexs.toString() + "----------------");
    Get.to(PhotoViewGalleryScreen(
      images: ee.toSet().toList(), //传入图片list
      index: indexs, //传入当前点击的图片的index
      heroTag: indexs.toString(), //传入当前点击的图片的hero tag （可选）
    ));
  }

  /// 根据消息获得组件
  _getMessageComponent(V2TimMessage message) {
    if (message.status == 6) {
      return message.isSelf
          ? Container(
              width: width(345),
              alignment: Alignment.center,
              padding: EdgeInsets.only(right: width(29)),
              child: Text(
                "你撤回了一条消息",
                style: TextStyle(
                  color: ZdColor.rgba(153, 153, 153, 1),
                ),
                textAlign: TextAlign.center,
              ),
            )
          : Container(
              width: width(345),
              alignment: Alignment.center,
              child: Text(
                "对方撤回了一条消息",
                style: TextStyle(color: ZdColor.rgba(153, 153, 153, 1)),
                textAlign: TextAlign.center,
              ));
    } else {
      //文字类型
      if (message.elemType == 1 && message.status != 6) {
        //转换为文字类型
        V2TimTextElem textElem = message.textElem;

        //判断是否本人
        return message.isSelf == true
            //单条消息样式
            ? Row(
                children: [
                  //TODO 已读   需要逻辑支撑
                  Container(
                    margin: EdgeInsets.only(top: 12, right: width(5)),
                    alignment: Alignment.centerRight,
                    child: Text(
                      message.isPeerRead == true ? "已读" : "未读",
                      style: TextStyle(
                        fontSize: sp(11),
                        color: Colors.black26,
                        fontFamily: 'Poppins',
                      ),
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      if (message.textElem.text.substring(0, 4) == "www." ||
                          message.textElem.text.substring(0, 4) == "http") {
                        Get.to(WebViewExample(
                          url: message.textElem.text,
                        ));
                      }
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.black12, width: 0.5),
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(20),
                          bottomLeft: Radius.circular(20),
                          bottomRight: Radius.circular(20),
                        ),
                        color: ZdColor.rgba(0, 220, 169, 1),
                      ),
                      padding: EdgeInsets.all(width(10)),
                      margin: EdgeInsets.only(right: width(8)),
                      alignment: Alignment.centerRight,
                      child: ConstrainedBox(
                        constraints: BoxConstraints(
                            maxWidth: width(240),
                            maxHeight: 350,
                            minHeight: 22),
                        child: Text(
                          textElem.text.toString(),
                          style: TextStyle(
                              fontSize: sp(15),
                              color: Colors.white,
                              fontFamily: 'Poppins'),
                        ),
                      ),
                    ),
                  ),
                ],
              )
            //else
            : Row(
                children: [
                  InkWell(
                    onTap: () {
                      if (message.textElem.text.substring(0, 4) == "www." ||
                          message.textElem.text.substring(0, 4) == "http") {
                        Get.to(WebViewExample(
                          url: message.textElem.text,
                        ));
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.black12, width: 0.5),
                          borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(20),
                            bottomRight: Radius.circular(20),
                            topRight: Radius.circular(20),
                          ),
                          color: Colors.white),
                      padding: EdgeInsets.all(10.0),
                      margin: EdgeInsets.only(left: 10),
                      child: ConstrainedBox(
                        constraints: BoxConstraints(
                            maxWidth: width(240),
                            maxHeight: 350,
                            minHeight: 22),
                        child: Text(
                          textElem.text.toString(),
                          style: TextStyle(
                              fontSize: sp(15),
                              fontWeight: FontWeight.w400,
                              fontFamily: 'Poppins'),
                        ),
                      ),
                    ),
                  ),
                  // Container(
                  //   margin: EdgeInsets.only(top: 12, left: width(5)),
                  //   alignment: Alignment.centerRight,
                  //   child: Text(
                  //     message.isRead == true ? "已读" : "未读",
                  //     style: TextStyle(fontSize: sp(11), color: Colors.black26),
                  //   ),
                  // )
                ],
              );
      } else if (message.elemType == 3) {
        V2TimImageElem node = message.imageElem;

        return InkWell(
          onTap: () {
            getIndex(message.msgID);
          },
          child: Row(
            children: [
              message.isSelf
                  ? Container(
                      margin: EdgeInsets.only(top: 12, right: width(5)),
                      alignment: Alignment.centerRight,
                      child: Text(
                        message.isPeerRead == true ? "已读" : "未读",
                        style:
                            TextStyle(fontSize: sp(11), color: Colors.black26),
                      ),
                    )
                  : SizedBox(),
              Container(
                margin: EdgeInsets.only(
                  left: !message.isSelf ? width(0) : width(5),
                  right: message.isSelf ? width(5) : width(0),
                ),
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(7),
                    // clipBehavior: ,
                    child: Container(
                        height: 140,
                        width: width(70),
                        child: message.isSelf
                            ? Image.asset(
                                node.path,
                                fit: BoxFit.cover,
                                errorBuilder: (context, Object error,
                                    StackTrace stackTrace) {
                                  return CachedNetworkImage(
                                    imageUrl: node.imageList[0].url,
                                    fit: BoxFit.cover,
                                    placeholder: (context, url) =>
                                        new Container(
                                      child: new Center(
                                        child: new CircularProgressIndicator(),
                                      ),
                                    ),
                                  );
                                },
                              )
                            : CachedNetworkImage(
                                imageUrl: node.imageList[0].url,
                                fit: BoxFit.cover,
                                placeholder: (context, url) => new Container(
                                  child: new Center(
                                    child: new CircularProgressIndicator(),
                                  ),
                                ),
                              ))),
              ),
            ],
          ),
        );
      }
      //
      // 视频消息
      if (message.elemType == 5) {
        V2TimVideoElem node = message.videoElem;
        // String path = node.snapshotPath == null || node.snapshotPath == ''
        //     ? (_tempPath + "/" + node.snapshotPath)
        //     : node.snapshotPath;

        return InkWell(
            onTap: () {
              Get.to(() => VideoMessage(message: message));
            },
            child: Row(
              children: [
                message.isSelf
                    ? Container(
                        margin: EdgeInsets.only(top: 12, right: width(5)),
                        alignment: Alignment.centerRight,
                        child: Text(
                          message.isPeerRead == true ? "已读" : "未读",
                          style: TextStyle(
                              fontSize: sp(11), color: Colors.black26),
                        ),
                      )
                    : SizedBox(),
                Container(
                  margin: EdgeInsets.only(
                    left: !message.isSelf ? width(0) : width(5),
                    right: message.isSelf ? width(5) : width(0),
                  ),
                  child: Stack(
                    children: [
                      ClipRRect(
                          borderRadius: BorderRadius.circular(7),
                          // clipBehavior: ,
                          child: Container(
                            height: width(160),
                            width: width(160),
                            child: message.isSelf
                                ? Image.asset(node.snapshotPath,
                                    fit: BoxFit.fill, errorBuilder: (context,
                                        Object error, StackTrace stackTrace) {
                                    return CachedNetworkImage(
                                      imageUrl: node.snapshotUrl,
                                      fit: BoxFit.cover,
                                      placeholder: (context, url) =>
                                          new Container(
                                        child: new Center(
                                          child:
                                              new CircularProgressIndicator(),
                                        ),
                                      ),
                                    );
                                  })
                                : CachedNetworkImage(
                                    imageUrl: node.snapshotUrl,
                                    fit: BoxFit.fill,
                                  ),
                          )),
                      Positioned(
                        child: Container(
                            width: width(160),
                            height: width(160),
                            child: Icon(
                              Icons.play_circle_outline,
                              color: Colors.white,
                              size: 40,
                            )),
                      ),
                    ],
                  ),
                ),
              ],
            ));
      } else if (message.elemType == 2) {
        V2TimCustomElem customElem = message.customElem;
        if (customElem.extension == "images") {
          List<V2TimImage> a = [];
          a.add(V2TimImage(type: 1, url: customElem.data));
          return Row(
            children: [
              /// ======================
              message.isSelf
                  ? Container(
                      margin: EdgeInsets.only(top: 12, right: width(5)),
                      alignment: Alignment.centerRight,
                      child: Text(
                        message.isPeerRead == true ? "已读" : "未读",
                        style:
                            TextStyle(fontSize: sp(11), color: Colors.black26),
                      ),
                    )
                  : SizedBox(),
              InkWell(
                  onTap: () {
                    getIndex(message.msgID);
                  },
                  child: Container(
                    margin: EdgeInsets.only(
                      left: message.isSelf ? width(0) : width(5),
                      right: message.isSelf ? width(5) : width(0),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(7),
                      // clipBehavior: ,
                      child: Container(
                        height: 140,
                        width: width(70),
                        child: CachedNetworkImage(
                          imageUrl: customElem.data,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  )),
            ],
          );
        } else if (customElem.extension == "mp4") {
          return Row(
            children: [
              message.isSelf
                  ? Container(
                      margin: EdgeInsets.only(top: 12, right: width(5)),
                      alignment: Alignment.centerRight,
                      child: Text(
                        message.isPeerRead == true ? "已读" : "未读",
                        style:
                            TextStyle(fontSize: sp(11), color: Colors.black26),
                      ),
                    )
                  : SizedBox(),
              InkWell(
                  onTap: () {
                    Get.to(() => VideoMessage(url: customElem.data));
                  },
                  child: Container(
                    margin: EdgeInsets.only(
                      left: !message.isSelf ? width(0) : width(5),
                      right: message.isSelf ? width(5) : width(0),
                    ),
                    child: Stack(
                      children: [
                        ClipRRect(
                            borderRadius: BorderRadius.circular(7),
                            // clipBehavior: ,
                            child: Container(
                              height: width(160),
                              width: width(160),
                              child: CachedNetworkImage(
                                imageUrl: customElem.desc,
                                fit: BoxFit.fill,
                              ),
                            )),
                        Positioned(
                          child: Container(
                              width: width(160),
                              alignment: Alignment.center,
                              height: width(160),
                              child: Icon(
                                Icons.play_circle_outline,
                                color: Colors.white,
                                size: 40,
                              )),
                        ),
                      ],
                    ),
                  )),
            ],
          );
        } else if (customElem.desc == "离线") {
          //判断是否本人
          return message.isSelf == true
              //单条消息样式
              ? Row(
                  children: [
                    //TODO 已读   需要逻辑支撑
                    Container(
                      margin: EdgeInsets.only(top: 12, right: width(5)),
                      alignment: Alignment.centerRight,
                      child: Text(
                        message.isPeerRead == true ? "已读" : "未读",
                        style:
                            TextStyle(fontSize: sp(11), color: Colors.black26),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        if (message.textElem.text.substring(0, 4) == "www." ||
                            message.textElem.text.substring(0, 4) == "http") {
                          Get.to(WebViewExample(
                            url: message.textElem.text,
                          ));
                        }
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.black12, width: 0.5),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                            bottomRight: Radius.circular(20),
                          ),
                          color: ZdColor.rgba(0, 220, 169, 1),
                        ),
                        padding: EdgeInsets.all(width(10)),
                        margin: EdgeInsets.only(right: width(8)),
                        alignment: Alignment.centerRight,
                        child: ConstrainedBox(
                          constraints: BoxConstraints(
                              maxWidth: width(240),
                              maxHeight: 350,
                              minHeight: 22),
                          child: Text(
                            customElem.data.toString(),
                            style: TextStyle(
                                fontSize: sp(15), color: Colors.white),
                          ),
                        ),
                      ),
                    ),
                  ],
                )
              //else
              : Row(
                  children: [
                    InkWell(
                      onTap: () {
                        if (message.textElem.text.substring(0, 4) == "www." ||
                            message.textElem.text.substring(0, 4) == "http") {
                          Get.to(WebViewExample(
                            url: message.textElem.text,
                          ));
                        }
                      },
                      child: Container(
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            border:
                                Border.all(color: Colors.black12, width: 0.5),
                            borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(20),
                              bottomRight: Radius.circular(20),
                              topRight: Radius.circular(20),
                            ),
                            color: Colors.white),
                        padding: EdgeInsets.all(10.0),
                        margin: EdgeInsets.only(left: 10),
                        child: ConstrainedBox(
                          constraints: BoxConstraints(
                              maxWidth: width(240),
                              maxHeight: 350,
                              minHeight: 22),
                          child: Text(
                            customElem.data.toString(),
                            style: TextStyle(
                                fontSize: sp(15), fontWeight: FontWeight.w400),
                          ),
                        ),
                      ),
                    ),
                    // Container(
                    //   margin: EdgeInsets.only(top: 12, left: width(5)),
                    //   alignment: Alignment.centerRight,
                    //   child: Text(
                    //     message.isRead == true ? "已读" : "未读",
                    //     style: TextStyle(fontSize: sp(11), color: Colors.black26),
                    //   ),
                    // )
                  ],
                );
        } else if (customElem.extension == "au") {
          return message.isSelf
              ? InkWell(
                  onTap: () {
                    //print("语音=================================" + node.url);
                    // print("语音=================================" + node.path);
                    setState(() {
                      message.isPlay = !message.isPlay;
                    });
                    if (message.isPlay) {
                      playByPath(customElem.data, "url");
                    } else {
                      pause();
                    }
                  },
                  child: Row(
                    children: [
                      message.isSelf
                          ? Container(
                              margin: EdgeInsets.only(top: 12, right: width(5)),
                              alignment: Alignment.centerRight,
                              child: Text(
                                message.isPeerRead == true ? "已读" : "未读",
                                style: TextStyle(
                                    fontSize: sp(11), color: Colors.black26),
                              ),
                            )
                          : SizedBox(),
                      Container(
                        margin: EdgeInsets.only(
                          left: message.isSelf ? width(0) : width(5),
                          right: message.isSelf ? width(5) : width(0),
                        ),
                        child: Row(
                          children: [
                            Container(
                                margin: EdgeInsets.only(right: 8),
                                decoration: BoxDecoration(
                                  border: Border.all(
                                      color: Colors.black12, width: 0.5),
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(20),
                                    bottomLeft: Radius.circular(20),
                                    bottomRight: Radius.circular(20),
                                  ),
                                  color: ZdColor.rgba(0, 220, 169, 1),
                                ),
                                padding: EdgeInsets.all(width(10)),
                                alignment: Alignment.centerRight,
                                child: ConstrainedBox(
                                  constraints: BoxConstraints(
                                      maxWidth: 140.0, maxHeight: 350),
                                  child: Row(
                                    children: [
                                      Text(
                                        "语音消息:  " + customElem.desc + "s",
                                        style: TextStyle(
                                            fontSize: sp(15),
                                            color: Colors.white),
                                        maxLines: 16,
                                        softWrap: true,
                                      ),
                                      !message.isPlay
                                          ? Container(
                                              margin: EdgeInsets.only(left: 10),
                                              child: Image.asset(
                                                "images/yuyin-左.png",
                                                height: 20,
                                                width: 20,
                                              ),
                                            )
                                          : Container(
                                              margin: EdgeInsets.only(left: 10),
                                              child: Image.asset(
                                                "images/yybf-zuo.gif",
                                                height: 20,
                                                width: width(20),
                                              ),
                                            ),
                                    ],
                                  ),
                                )),
                          ],
                        ),
                      ),
                    ],
                  ),
                )
              : InkWell(
                  onTap: () {
                    //todo 安卓不能识别ios MP3文件
                    // print("语音=================================" + node.url);
                    //print("语音=================================" + node.path);
                    setState(() {
                      message.isPlay = !message.isPlay;
                    });
                    //print(flagVoice);
                    String url =
                        "http://sy.sycdn.kuwo.cn/1afa8db295eba1326ca6d5c96b4616dd/60fa4c0e/resource/n1/84/19/2974502628.mp3";
                    //print("语音================================" + node.url);
                    if (message.isPlay) {
                      playByPath(customElem.data, "url");
                    } else {
                      pause();
                    }
                  },
                  child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.black12, width: 0.5),
                          borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(20),
                            bottomRight: Radius.circular(20),
                            topRight: Radius.circular(20),
                          ),
                          color: Colors.white),
                      padding: EdgeInsets.all(10.0),
                      margin: EdgeInsets.only(left: 10),
                      child: ConstrainedBox(
                        constraints:
                            BoxConstraints(maxWidth: 140.0, maxHeight: 350),
                        child: Row(
                          children: [
                            !message.isPlay
                                ? Container(
                                    margin: EdgeInsets.only(left: 10),
                                    child: Image.asset(
                                      "images/yuyin-you.png",
                                      height: 20,
                                      width: 20,
                                    ),
                                  )
                                : Container(
                                    margin: EdgeInsets.only(left: 10),
                                    child: Image.asset(
                                      "images/yybf-you.gif",
                                      height: 20,
                                      width: width(20),
                                    ),
                                  ),
                            Text(
                              "语音消息: " + customElem.desc + "s",
                              style: TextStyle(
                                  fontSize: sp(15), color: Colors.black),
                              maxLines: 16,
                              softWrap: true,
                            ),
                          ],
                        ),
                      )),
                );
        } else if (customElem.data == "对方开启了好友验证，您可以重新添加对方为好友") {
          return Container(
            alignment: Alignment.center,
            width: width(345),
            margin: EdgeInsets.only(right: width(8)),
            child: Text(
              customElem.data,
              style: TextStyle(color: ZdColor.rgba(153, 153, 153, 1)),
            ),
          );
        } else if (!message.isSelf && customElem.desc == 'start') {
          widget.name("正在输入中...");
          return SizedBox();
        } else if (!message.isSelf && customElem.desc == 'end') {
          widget.name(message.nickName);
          return SizedBox();
        } else if (customElem.desc == 'start') {
          return SizedBox();
        } else if (customElem.desc == 'end') {
          return SizedBox();
        }
      } else if (message.elemType == 4) {
        V2TimSoundElem node = message.soundElem;
        // vioceUid = node.UUID;

        //url.substring(vioceUid.length);
        //print(url);
        return message.isSelf
            ? InkWell(
                onTap: () {
                  print("语音=================================" + node.url);
                  print("语音=================================" + node.path);
                  setState(() {
                    message.isPlay = !message.isPlay;
                  });
                  if (message.isPlay) {
                    playByPath(node.path, "file");
                  } else {
                    pause();
                  }

                  //print(flagVoice);
                },
                child: Row(
                  children: [
                    message.isSelf
                        ? Container(
                            margin: EdgeInsets.only(top: 12, right: width(5)),
                            alignment: Alignment.centerRight,
                            child: Text(
                              message.isPeerRead == true ? "已读" : "未读",
                              style: TextStyle(
                                  fontSize: sp(11), color: Colors.black26),
                            ),
                          )
                        : SizedBox(),
                    Container(
                      child: Row(
                        children: [
                          Container(
                              margin: EdgeInsets.only(right: 8),
                              decoration: BoxDecoration(
                                border: Border.all(
                                    color: Colors.black12, width: 0.5),
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(20),
                                  bottomLeft: Radius.circular(20),
                                  bottomRight: Radius.circular(20),
                                ),
                                color: ZdColor.rgba(0, 220, 169, 1),
                              ),
                              padding: EdgeInsets.all(width(10)),
                              alignment: Alignment.centerRight,
                              child: ConstrainedBox(
                                constraints: BoxConstraints(
                                    maxWidth: 140.0, maxHeight: 350),
                                child: Row(
                                  children: [
                                    Text(
                                      "语音消息:  " +
                                          node.duration.toString() +
                                          "s",
                                      style: TextStyle(
                                          fontSize: sp(15),
                                          color: Colors.white),
                                      maxLines: 16,
                                      softWrap: true,
                                    ),
                                    !message.isPlay
                                        ? Container(
                                            margin: EdgeInsets.only(left: 10),
                                            child: Image.asset(
                                              "images/yuyin-左.png",
                                              height: 20,
                                              width: 20,
                                            ),
                                          )
                                        : Container(
                                            margin: EdgeInsets.only(left: 10),
                                            child: Image.asset(
                                              "images/yybf-zuo.gif",
                                              height: 20,
                                              width: width(20),
                                            ),
                                          ),
                                  ],
                                ),
                              )),
                        ],
                      ),
                    ),
                  ],
                ),
              )
            : InkWell(
                onTap: () {
                  //todo 安卓不能识别ios MP3文件
                  print("语音=================================" + node.url);
                  print("语音=================================" + node.path);
                  setState(() {
                    message.isPlay = !message.isPlay;
                  });
                  //print(flagVoice);
                  String url =
                      "http://sy.sycdn.kuwo.cn/1afa8db295eba1326ca6d5c96b4616dd/60fa4c0e/resource/n1/84/19/2974502628.mp3";
                  print("语音================================" + node.url);
                  if (message.isPlay) {
                    playByPath(node.url, "url");
                  } else {
                    pause();
                  }
                },
                child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.black12, width: 0.5),
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(20),
                          bottomRight: Radius.circular(20),
                          topRight: Radius.circular(20),
                        ),
                        color: Colors.white),
                    padding: EdgeInsets.all(10.0),
                    margin: EdgeInsets.only(left: 10),
                    child: ConstrainedBox(
                      constraints:
                          BoxConstraints(maxWidth: 140.0, maxHeight: 350),
                      child: Row(
                        children: [
                          !message.isPlay
                              ? Container(
                                  margin: EdgeInsets.only(left: 10),
                                  child: Image.asset(
                                    "images/yuyin-you.png",
                                    height: 20,
                                    width: 20,
                                  ),
                                )
                              : Container(
                                  margin: EdgeInsets.only(left: 10),
                                  child: Image.asset(
                                    "images/yybf-you.gif",
                                    height: 20,
                                    width: width(20),
                                  ),
                                ),
                          Text(
                            "语音消息: " + node.duration.toString() + "s",
                            style: TextStyle(
                                fontSize: sp(15), color: Colors.black),
                            maxLines: 16,
                            softWrap: true,
                          ),
                        ],
                      ),
                    )),
              );
      }
      // 图片消息
      if (message.elemType == 3) {
        V2TimImageElem node = message.imageElem;

        return InkWell(
          onTap: () {
            getIndex(message.msgID);
          },
          child: Row(
            children: [
              message.isSelf
                  ? Container(
                      margin: EdgeInsets.only(top: 12, right: width(5)),
                      alignment: Alignment.centerRight,
                      child: Text(
                        message.isPeerRead == true ? "已读" : "未读",
                        style:
                            TextStyle(fontSize: sp(11), color: Colors.black26),
                      ),
                    )
                  : SizedBox(),
              Container(
                  margin: EdgeInsets.only(
                    left: !message.isSelf ? width(0) : width(5),
                    right: message.isSelf ? width(5) : width(0),
                  ),
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(7),
                      // clipBehavior: ,
                      child: Container(
                          height: 140,
                          width: width(70),
                          child: message.isSelf
                              ? Image.asset(node.path, fit: BoxFit.cover,
                                  errorBuilder: (context, Object error,
                                      StackTrace stackTrace) {
                                  return CachedNetworkImage(
                                    imageUrl: node.imageList[0].url,
                                    fit: BoxFit.cover,
                                    placeholder: (context, url) =>
                                        new Container(
                                      child: new Center(
                                        child: new CircularProgressIndicator(),
                                      ),
                                    ),
                                  );
                                })
                              : CachedNetworkImage(
                                  imageUrl: node.imageList[0].url,
                                  fit: BoxFit.cover,
                                  placeholder: (context, url) => new Container(
                                    child: new Center(
                                      child: new CircularProgressIndicator(),
                                    ),
                                  ),
                                )))),
            ],
          ),
        );
      } else {
        return Center(
          child: Text("暂不支持的数据类型"),
        );
      }
    }
  }

  @override
  void initState() {
    super.initState();
    _initRecordMp3();

    ///初始化方法的监听
    recordPlugin.responseFromInit.listen((data) {
      if (data) {
        print("初始化成功");
      } else {
        print("初始化失败");
      }
    });
    recordPlugin.responsePlayStateController.listen((data) {
      print("播放路径   " + data.playPath);
      print("播放状态   " + data.playState);
      if (data.playState == "complete") {
        currentMessageList.forEach((element) {
          element.isPlay = false;
        });
        setState(() {});
      }
    });
  }

  ///停止语音录制的方法
  void stop() {
    recordPlugin.stop();
  }

  ///播放语音的方法
  void play() {
    recordPlugin.play();
  }

  ///播放指定路径录音文件  url为iOS播放网络语音，file为播放本地语音文件
  void playByPath(String path, String type) {
    recordPlugin.playByPath(path, type);
  }

  ///暂停|继续播放
  void pause() {
    recordPlugin.pausePlay();
  }

  void stopPlay() {
    recordPlugin.stopPlay();
  }

  @override
  void dispose() {
    super.dispose();
    recordPlugin.dispose();
  }

  ///初始化语音录制的方法
  void _initRecordMp3() async {
    recordPlugin.init();
  }

  final List<String> actions = [
    '复制',
    '转发',
    '收藏',
    '撤回',
    '多选',
    '删除',
  ];
  bool flag = false;
  getHistroyList(currentMessageMap, messageList) {
    if (currentMessageMap != null) {
      messageList = currentMessageMap[widget.conversationID];
    }
    if (messageList == null) {
      return Center(child: Loading());
    }

    hasNoRead = messageList.any((element) {
      return !element.isSelf && !element.isRead;
    });
    setState(() {
      currentMessageList = messageList;
    });
    ee = [];
    currentMessageList.forEach((element) {
      if (element.status == 6) {
        element.localCustomInt = 1;
      }

      if (element.elemType == 3) {
        ee.add(V2TimImage(
            type: element.imageElem.imageList[0].type,
            url: element.imageElem.imageList[0].url,
            UUID: element.msgID));
      } else if (element.elemType == 2 &&
          element.customElem.extension == "images") {
        ee.add(V2TimImage(
            type: 1, url: element.customElem.data, UUID: element.msgID));
      }
    });
    ee.forEach((element) {
      print("============================123;::" + element.toJson().toString());
    });
    if (widget.type == 2) {
      // 如果有未读，设置成已读，否者会触发
      TencentImSDKPlugin.v2TIMManager
          .getMessageManager()
          .markGroupMessageAsRead(groupID: widget.groupID)
          .then((res) {
        if (res.code == 0) {
          print("设置群组会话已读 成功");
        } else {
          print("设置群组会话已读 失败");
        }
      });
    }
    if (hasNoRead) {
      if (widget.type == 1) {
        print("设置个人会话已读");
        print(
            "设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读设置个人会话已读");
        TencentImSDKPlugin.v2TIMManager
            .getMessageManager()
            .markC2CMessageAsRead(userID: widget.userID)
            .then((res) {
          if (res.code == 0) {
            print("设置个人会话已读 成功");
          } else {
            print("设置个人会话已读 失败");
          }
        });
      }
    } else {
      print("没有未读");
    }
  }

  @override
  Widget build(BuildContext context) {
    Map<String, List<V2TimMessage>> currentMessageMap =
        Provider.of<CurrentMessageListModel>(context).messageMap;
    List<V2TimMessage> messageList = <V2TimMessage>[];
    getHistroyList(currentMessageMap, messageList);
    print("添加了一条发送中的消息 刷新聊天列表");

    //TODO 刷新会反过来 注意吧 需要新方法
    return ListView(
      shrinkWrap: true,
      reverse: currentMessageList.length < 6 ? false : true,
      controller: widget.controller,
      children: currentMessageList.length < 6
          ? currentMessageList
              .map((item) => Padding(
                    padding: EdgeInsets.all(8),
                    child: Container(
                      child: Row(
                        mainAxisAlignment: item.isSelf == true
                            ? MainAxisAlignment.end
                            : MainAxisAlignment.start,
                        children: <Widget>[
                          widget.checkMessage
                              ? DefCheckBoxWidget(
                                  value: item.localCustomInt == 6,
                                  onTap: (d) async {
                                    //showToast(item.textElem.text);
                                    if (d) {
                                      item.localCustomInt = 6;
                                      await TencentImSDKPlugin
                                          .v2TIMManager.v2TIMMessageManager
                                          .setLocalCustomInt(
                                              msgID: item.msgID,
                                              localCustomInt: 6);
                                    } else {
                                      item.localCustomInt = 0;
                                      await TencentImSDKPlugin
                                          .v2TIMManager.v2TIMMessageManager
                                          .setLocalCustomInt(
                                              msgID: item.msgID,
                                              localCustomInt: 0);
                                    }
                                    setState(() {});
                                    // showToast(
                                    //item.isCheckBox.toString());
                                  })
                              : SizedBox(),
                          Offstage(
                              offstage: item.isSelf == true,
                              child: Row(
                                children: [
                                  InkWell(
                                      onTap: () {
                                        !item.isSelf
                                            ? Get.to(
                                                () => ConversationFriendPage(
                                                      type: 4,
                                                      model: AddressBookModel(
                                                        name: item.nickName,
                                                        userId: item.userID,
                                                        headerUrl: item.faceUrl,
                                                      ),
                                                    ))
                                            : print("123");
                                      },
                                      child: item.localCustomInt == 1
                                          ? SizedBox()
                                          : faceHeader(item)),
                                ],
                              )),
                          //头像

                          //长按消息组件

                          WPopupMenu(
                              pageMaxChildCount: 4,
                              menuWidth: width(250),
                              onValueChanged: (value) async {
                                switch (value) {
                                  case 0:
                                    String textValue = "";

                                    showToast(item.status.toString());
                                    if (item.elemType == 1 &&
                                        item.status != 6) {
                                      textValue = item.textElem.text;
                                      showToast("已复制");
                                    } else {
                                      showToast("只能复制文字！！");
                                      textValue = "";
                                    }

                                    return Clipboard.setData(
                                        ClipboardData(text: textValue ?? ""));
                                  case 1:
                                    Get.to(GetContactsWidget(
                                      someMessage: [item],
                                    )).then((value) {
                                      setState(() {});
                                    });
                                    return null;

                                  case 4:
                                    // setState(() {
                                    //   checkMessage = false;
                                    //   _focusNode.unfocus();
                                    //   emojo = true;
                                    //   favorite = true;
                                    //   flag = false;
                                    // });

                                    Navigator.push(
                                        context,
                                        FadeRoute(SelectMessageWidget(
                                            widget.conversationID,
                                            item.nickName)));
                                    return null;

                                  case 5:
                                    deleteMessageFromLocalStorage() async {
                                      V2TimCallback res =
                                          await TencentImSDKPlugin.v2TIMManager
                                              .getMessageManager()
                                              .deleteMessageFromLocalStorage(
                                                  msgID: item.msgID);
                                      if (res.code == 0) {
                                        showToast("删除成功");
                                      }
                                      print(res.toJson());
                                    }
                                    deleteMessageFromLocalStorage();
                                    setState(() {
                                      return currentMessageList.remove(item);
                                    });
                                    return null;
                                  case 2:
                                    List list = [];
                                    if (item.elemType == 1) {
                                      list.add(json.encode({
                                        "msgId": item.msgID,
                                        "roomJid": "0",
                                        "type": "5",
                                        "msg": item.textElem.text
                                      }));
                                    } else if (item.elemType == 3) {
                                      //图片
                                      list.add(json.encode({
                                        "msgId": item.msgID,
                                        "roomJid": "1",
                                        "type": "1",
                                        "url": item.imageElem.imageList[0].url,
                                        "msg": item.imageElem.imageList[0].url
                                      }));
                                    } else if (item.elemType == 4) {
                                      //音频
                                      list.add(json.encode({
                                        "msgId": item.msgID,
                                        "roomJid": "1",
                                        "type": "4",
                                        "url": item.soundElem.url,
                                        "msg": item.soundElem.url,
                                        "fileLength":
                                            item.soundElem.duration.toString()
                                      }));
                                    } else if (item.elemType == 5) {
                                      //视频
                                      list.add(json.encode({
                                        "msgId": item.msgID,
                                        "roomJid": "1",
                                        "type": "2",
                                        "url": item.videoElem.snapshotUrl,
                                        "msg": item.videoElem.videoUrl,
                                        "fileLength":
                                            item.videoElem.duration.toString()
                                      }));

                                      json.encode(list);
                                    }
                                    list.forEach((element) {
                                      print(
                                          "******************************************************");
                                      print("*        " + element.toString());
                                      print(
                                          "******************************************************");
                                    });
                                    await CollectDao.addCollect("", "", "",
                                        roomJid: "", emoji: list.toString());
                                    return null;
                                }
                              },
                              actions: actions,
                              child: _getMessageComponent(item)),

                          Offstage(
                              offstage: !item.isSelf,
                              child: Row(
                                children: [
                                  InkWell(
                                      onTap: () {
                                        !item.isSelf
                                            ? Get.to(
                                                () => ConversationFriendPage(
                                                      model: AddressBookModel(
                                                        name: item.nickName,
                                                        userId: item.userID,
                                                        headerUrl: item.faceUrl,
                                                      ),
                                                    ))
                                            : print("123");
                                      },
                                      child: item.localCustomInt == 1
                                          ? SizedBox()
                                          : faceHeader(item)),
                                ],
                              )),
                        ],
                      ),
                    ),
                  ))
              .toList()
          : currentMessageList.reversed
              .map((item) => Padding(
                    padding: EdgeInsets.all(8),
                    child: Container(
                      child: Row(
                        mainAxisAlignment: item.isSelf == true
                            ? MainAxisAlignment.end
                            : MainAxisAlignment.start,
                        children: <Widget>[
                          widget.checkMessage
                              ? DefCheckBoxWidget(
                                  value: item.localCustomInt == 6,
                                  onTap: (d) async {
                                    //showToast(item.textElem.text);
                                    if (d) {
                                      item.localCustomInt = 6;
                                      await TencentImSDKPlugin
                                          .v2TIMManager.v2TIMMessageManager
                                          .setLocalCustomInt(
                                              msgID: item.msgID,
                                              localCustomInt: 6);
                                    } else {
                                      item.localCustomInt = 0;
                                      await TencentImSDKPlugin
                                          .v2TIMManager.v2TIMMessageManager
                                          .setLocalCustomInt(
                                              msgID: item.msgID,
                                              localCustomInt: 0);
                                    }
                                    setState(() {});
                                    // showToast(
                                    //item.isCheckBox.toString());
                                  })
                              : SizedBox(),
                          Offstage(
                              offstage: item.isSelf == true,
                              child: Row(
                                children: [
                                  InkWell(
                                      onTap: () {
                                        !item.isSelf
                                            ? Get.to(
                                                () => ConversationFriendPage(
                                                      type: 4,
                                                      model: AddressBookModel(
                                                        name: item.nickName,
                                                        userId: item.userID,
                                                        headerUrl: item.faceUrl,
                                                      ),
                                                    ))
                                            : print("123");
                                      },
                                      child: item.localCustomInt == 1
                                          ? SizedBox()
                                          : faceHeader(item)),
                                ],
                              )),
                          //头像

                          //长按消息组件

                          WPopupMenu(
                              pageMaxChildCount: 4,
                              menuWidth: width(250),
                              onValueChanged: (value) async {
                                switch (value) {
                                  case 0:
                                    String textValue = "";
                                    if (item.elemType == 1 &&
                                        item.status != 6) {
                                      textValue = item.textElem.text;
                                      showToast("已复制");
                                    } else {
                                      showToast("只能复制文字！！");
                                      textValue = "";
                                    }
                                    return Clipboard.setData(
                                        ClipboardData(text: textValue ?? ""));
                                  case 1:
                                    Get.to(GetContactsWidget(
                                      someMessage: [item],
                                    ));
                                    return null;
                                  case 3:
                                    V2TimCallback call =
                                        await TencentImSDKPlugin
                                            .v2TIMManager.v2TIMMessageManager
                                            .revokeMessage(msgID: item.msgID);
                                    if (call.desc == 'ok') {
                                      showToast('撤回成功');
                                    } else {
                                      showToast('已经超过三分钟');
                                    }

                                    return null;
                                  case 4:
                                    // setState(() {
                                    //   checkMessage = false;
                                    //   _focusNode.unfocus();
                                    //   emojo = true;
                                    //   favorite = true;
                                    //   flag = false;
                                    // });

                                    Navigator.push(
                                        context,
                                        FadeRoute(SelectMessageWidget(
                                            widget.conversationID,
                                            item.nickName)));
                                    return null;
                                  case 5:
                                    deleteMessageFromLocalStorage() async {
                                      V2TimCallback res =
                                          await TencentImSDKPlugin.v2TIMManager
                                              .getMessageManager()
                                              .deleteMessageFromLocalStorage(
                                                  msgID: item.msgID);
                                      if (res.code == 0) {
                                        showToast("删除成功");
                                      }
                                      print(res.toJson());
                                    }
                                    deleteMessageFromLocalStorage();
                                    setState(() {
                                      return currentMessageList.remove(item);
                                    });
                                    return null;
                                  case 2:
                                    List list = [];
                                    if (item.elemType == 1) {
                                      list.add(json.encode({
                                        "msgId": item.msgID,
                                        "roomJid": "0",
                                        "type": "5",
                                        "msg": item.textElem.text
                                      }));
                                    } else if (item.elemType == 3) {
                                      //图片
                                      list.add(json.encode({
                                        "msgId": item.msgID,
                                        "roomJid": "1",
                                        "type": "1",
                                        "url": item.imageElem.imageList[0].url,
                                        "msg": item.imageElem.imageList[0].url
                                      }));
                                    } else if (item.elemType == 4) {
                                      //音频
                                      list.add(json.encode({
                                        "msgId": item.msgID,
                                        "roomJid": "1",
                                        "type": "4",
                                        "url": item.soundElem.url,
                                        "msg": item.soundElem.url,
                                        "fileLength":
                                            item.soundElem.duration.toString()
                                      }));
                                    } else if (item.elemType == 5) {
                                      //视频
                                      list.add(json.encode({
                                        "msgId": item.msgID,
                                        "roomJid": "1",
                                        "type": "2",
                                        "url": item.videoElem.snapshotUrl,
                                        "msg": item.videoElem.videoUrl,
                                        "fileLength":
                                            item.videoElem.duration.toString()
                                      }));

                                      json.encode(list);
                                    }
                                    await CollectDao.addCollect("", "", "",
                                        roomJid: "", emoji: list.toString());
                                    return null;
                                }
                              },
                              actions: actions,
                              child: _getMessageComponent(item)),

                          Offstage(
                              offstage: !item.isSelf,
                              child: Row(
                                children: [
                                  InkWell(
                                      onTap: () {
                                        !item.isSelf
                                            ? Get.to(
                                                () => ConversationFriendPage(
                                                      model: AddressBookModel(
                                                        name: item.nickName,
                                                        userId: item.userID,
                                                        headerUrl: item.faceUrl,
                                                      ),
                                                    ))
                                            : print("123");
                                      },
                                      child: item.localCustomInt == 1
                                          ? SizedBox()
                                          : faceHeader(item)),
                                ],
                              )),
                        ],
                      ),
                    ),
                  ))
              .toList(),
    );
  }

  //40*40
  Container faceHeader(V2TimMessage message) {
    return Container(
        height: width(40),
        width: width(40),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6),
          color: Colors.greenAccent,
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(6),
          child: CachedNetworkImage(
            imageUrl: message.faceUrl == null || message.faceUrl == ""
                ? HEADER_URL
                : message.faceUrl,
            fit: BoxFit.cover,
          ),
        ));
  }
}
